package process_demo.blocking_queue_impl;

/**
 * @author haomin
 * @date 2022/04/25 21:04
 **/
public class MyArrayBlockingQueue {
    private long[] array;
    private int frontIndex; // 永远在队列的第一个元素位置
    private int rearIndex;  // 永远在队列的最后一个的下一个位置
    private int size;

    public MyArrayBlockingQueue(int capacity) {
        array = new long[capacity];
        frontIndex = 0;
        rearIndex = 0;
        size = 0;
    }

    public synchronized void put(long e) throws InterruptedException {
        // 判断队列是否已经满了
        while (array.length == size) {
            this.wait();
        }

        // 预期：队列一定不是满的

        array[rearIndex] = e;
        rearIndex++;
        if (rearIndex == array.length) {
            rearIndex = 0;
        }

        size++;

        notify();
    }

    public synchronized long take() throws InterruptedException {
        while (size == 0) {
            wait();
        }

        long e = array[frontIndex];
        frontIndex++;
        if (frontIndex == array.length) {
            frontIndex = 0;
        }
        size--;

        notify();

        return e;
    }
}